<ul class="category-tree">
<? foreach ($categories as $category): ?>
<?php
    $categoryId   = $category['Category']['id'];
    $categoryName = $category['Category']['name'];
    $isSub        = !empty($category['children']);
?>
    <li<? if($isSub): ?> class="sub"<? endif ?> value="<?= $categoryId ?>">
        <? if($isSub): ?>
        <a href="javascript:void(0)" class="toggle" onclick="toggleSub(this)">+</a>
        <? endif ?>
        <span class="actions">
            <?= $this->Html->link('obriši', '/admin_products/category_delete/' . $categoryId) ?>
        </span>
        <?= $this->Html->link($categoryName, '/admin_products/category_edit/' . $categoryId) ?>
        <? if($isSub): ?>
            <?= $this->element('category_tree', array(
                'categories' => $category['children']
            )) ?>
        <? endif ?>
    </li>
<? endforeach ?>
</ul>

<script type="text/javascript">
$(function(){
    $('.category-tree').sortable({
        revert: 'invalid',
        preservePlaceholderSize: true,
        preserveHelperSize:true,
        start: function() {
            $('#trash').show();
        },
        stop: function(e, ui) {
            $('#trash').hide();
            $(this).before('<button onclick="updatePositions(this)" class="update-reorder">Sačuvaj redosled</button>');
        }
    });
});
function toggleSub(a) {
    a = $(a);
    var ul = a.siblings('ul.category-tree');
    if (ul.is(':visible')) {
        ul.hide();
        a.html('+');
    } else {
        ul.show();
        a.html('-');
    }
}
function updatePositions(btn) {
    var ul = $(btn).siblings('ul.category-tree');
    var positions = [];
    ul.children('li').each(function(index){
        positions.push({
            id: $(this).attr('value'),
            position: index
        });
    });
    
    $.ajax({
       url: '/admin_products/category_positions_update',
       data: {positions: positions},
       beforeSend: function() {
           ul.addClass('loading');
       },
       complete: function(req) {
           ul.removeClass('loading');
           $(btn).remove();
           alert(req.responseText);
       }
    });
}
</script>